<?php
namespace app\index\controller;

use think\facade\View;
use hema\wechat\Map;
use app\index\model\Setting;
use app\index\model\Apply as ApplyModel;
use app\index\model\User as UserModel;
use think\facade\Session;

/**
 * 页面
 */
class Proxy extends Controller
{
    public function index()
    {
		View::assign('key', 'proxy');
		View::assign('title', '招商加盟');
		View::assign('description', '');
		View::assign('keywords', '');
		return View::fetch();
    }
    
    /**
     * 代理申请
     */
    public function add()
    {
        if ($this->request->isGet()) {
            if(isset($this->user['user'])){
                if($user = UserModel::getUser(['user_id' => $this->user['user']['user_id']])){
                    //更新session
                    Session::set('hema_user', [
            			'user' => $user,
            			'is_login' => true,
            		]);
                    if($user['status']['value'] == 30){
                        return $this->renderError('您已经是代理了');
                    }
                }else{
                    return $this->renderError('用户不存在');
                }
            }else{
               return $this->renderError('你还没有登录'); 
            }
            //检查申请记录
            if((new ApplyModel)->where(['user_id' => $user['user_id'],'apply_mode' => 40])->where('apply_status','<>',30)->find()){
                return $this->renderError('您的申请正在处理中，不要重复提交');
            }
            return $this->renderSuccess();
        }
        if ($this->request->isPost()) {
            $model = new ApplyModel;
            $data = $this->postData('data');
            $data['apply_status'] = 10; //待审核
            $data['apply_mode'] = 40;   //代理认证
            $data['user_id'] = $this->user['user']['user_id'];
            if ($model->action($data)) {
                return $this->renderSuccess('申请成功', '/user/apply/index');
            }
            $error = $model->getError() ?: '申请失败';
            return $this->renderError($error);
        }
        return redirect(url('proxy/add'));
    }
    
    /**
     * 地图
     */
    public function getpoint()
    {
        $map = new Map;
        $location = $map->getIp();//坐标信息
        $values = Setting::getItem('ability',0);
        View::layout(false);
        View::assign('wxmap_key', $values['wxmap']);
        View::assign('location', $location);
        return View::fetch();
    }
}
